//
//  PowerAddVC.swift
//  LeGou
//
//  Created by 刘亿前 on 2022/9/14.
//

import UIKit
import WebKit

class PowerAddVC: ZMViewController {

    @IBOutlet weak var topView: UIView!
    
    @IBOutlet weak var cityView: UIStackView!
    @IBOutlet weak var city: UILabel!
    
    @IBOutlet weak var numberTxt: ZMTextField!
    
    @IBOutlet weak var optionCollection: UICollectionView!
    
    @IBOutlet weak var optionHeight: NSLayoutConstraint!
    
    @IBOutlet weak var nextBtn: UIButton!
    
    @IBOutlet weak var detailInfoView: UIView!
    @IBOutlet weak var detailInfoHeight: NSLayoutConstraint!
    
    lazy var wkWeb: WKWebView = {
        let userContentController = WKUserContentController()
        let wkWebConfig = WKWebViewConfiguration()
        wkWebConfig.userContentController = userContentController
        wkWebConfig.allowsInlineMediaPlayback = true
        let web = WKWebView(frame: CGRect.zero, configuration: wkWebConfig)
        web.scrollView.showsVerticalScrollIndicator = false
        web.backgroundColor = .white
        web.navigationDelegate = self
        web.scrollView.bounces = false
        detailInfoView.addSubview(web)
        web.snp.makeConstraints { (make) in
            make.top.equalTo(54)
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.bottom.equalTo(-16)
        }
        return web
    }()
    
    var optionArr = [PowerOptionModel]()
    var numberStr = ""
    var cityArr = ["北京市", "北京市"]
    var saveHistory: ((_ number: String, _ city: [String])->())?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        setCollection()
        bindAction()
        requestOption()
        requestWeb()
    }

    func setUI() {
        title = "新增缴费"
        view.backgroundColor = "#F5F5F5".zm.hex()
        numberTxt.text = numberStr
        city.text = cityArr[1]
    }
    
    func setCollection() {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 12
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize(width: (SCREEN_W - 24 - 54) / 3, height: 57)
        optionCollection.delegate = self
        optionCollection.dataSource = self
        optionCollection.setCollectionViewLayout(layout, animated: true)
        optionCollection.register(UINib(nibName: "PowerAddOptionCell", bundle: nil), forCellWithReuseIdentifier: "PowerAddOptionCell")
    }
    
    // MARK: - bindAction
    func bindAction() {
        let cityTap = UITapGestureRecognizer()
        cityView.addGestureRecognizer(cityTap)
        cityTap.rx.event.subscribe(onNext: { [unowned self] recognizer in
            ZMProvinceCityView.show(false) { [unowned self] province, city, area in
                self.numberTxt.endEditing(true)
                self.cityArr = [province.name, city.name]
                self.city.text = city.name
            }
        }).disposed(by: disposeBag)
        
        nextBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            guard let number = self.numberTxt.text, number != "" else {
                return ZMToast.showToast(title: self.numberTxt.placeholder!)
            }
            let arr = self.optionArr.filter({return $0.select})
            if arr.count == 0 {
                return ZMToast.showToast(title: "请选择缴费金额")
            }
            self.requestCreate(arr[0], number)
            if let block = self.saveHistory {
                block(number, self.cityArr)
            }
        }).disposed(by: disposeBag)
        
        ZMPayManager.shard.payCallBack.subscribe(onNext:{ [unowned self] resp in
            switch resp {
            case .success:
                // 支付成功
                self.replace(PowerHistoryVC())
                break
            default:
                ZMToast.showToast(title: resp.rawValue)
            }
        }).disposed(by: disposeBag)
        
        wkWeb.scrollView.rx.observeWeakly(CGSize.self, "contentSize").subscribe(onNext: { [unowned self] (change) in
            self.detailInfoHeight.constant = change!.height + 70
        }).disposed(by: disposeBag)
    }
    
    func showPay(money : String, orderNo : String) {
        view.endEditing(true)
        let v = ZMUtil.loadNibViewFullScreen(nibName: OrderChoosePayView.self)
        v.price.text = money
        v.payMoney = Double(money) ?? 0
        v.onPayCallback = { [weak self, weak v] type in
            guard let v = v, let self = self else {return}
            var payType = ""
            switch type {
                case .alipay:
                    payType = "alipay"
                    break;
                case .wechat:
                    payType = "weixin"
                    break;
                case .balancePay:
                    payType = "yue"
                case .ckPay:
                    payType = "mallYue"
                case .integral:
                    payType = "integral"
            }
            var pa = ["orderNo" : orderNo, "payType" : payType] as [String : Any]
            if type == .balancePay || type == .ckPay {
                CommonService.shared.showPsdInput(title : "请输入交易密码", money: money, left : "", right : "") { psd, close in
                    pa["tradePwd"] = psd
                    self.sendPay(pa: pa, orderNo: orderNo, payType: payType) { ok in
                        close(ok)
                        if ok {
                            v.removeFromSuperview()
                        }
                    }
                }
            } else {
                self.sendPay(pa: pa, orderNo: orderNo, payType: payType) { ok in
                    v.removeFromSuperview()
                }
            }
        }
        APPWindow?.addSubview(v)
    }
    
    func sendPay(pa : [String : Any], orderNo : String, payType : String, complete:@escaping (_ ok : Bool)->()) {
        ZMToast.showActivity()
        VIPMallAPI.payInfo(pa).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            if payType == "yue" || payType == "mallYue" {
                // 支付成功
                self.replace(PowerHistoryVC())
            } else {
                let payStr = JSON(resp)["alipayRequest"].stringValue
                if payType == "weixin" {
                    ZMPayManager.shard.wechatPay(resp, orderNum: orderNo)
                } else {
                    ZMPayManager.shard.aliPayWithInfo(payStr, orderNum: orderNo)
                }
            }
            complete(true)
        }, onError: { _ in
            complete(false)
        }).disposed(by: self.disposeBag)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        optionCollection.reloadData()
        topView.layoutIfNeeded()
        topView.style.GradientLeftToRight(left: "#83AEF9".zm.hex(), right: "#2D7FDF".zm.hex())
        topView.zm.filletedCorner(8.0, [.topLeft, .topRight])
    }
}


extension PowerAddVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return optionArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PowerAddOptionCell", for: indexPath) as! PowerAddOptionCell
        let info = optionArr[indexPath.row]
        cell.number.text = info.faceValue.zm.toString(keep: 2)
        cell.price.text = "优惠价 \(info.sellPrice.zm.toString(keep: 2))元"
        if info.select {
            cell.bgView.backgroundColor = "#418AE5".zm.hex()
            cell.number.textColor = .white
            cell.price.textColor = .white
        } else {
            cell.bgView.backgroundColor = "#F5F5F5".zm.hex()
            cell.number.textColor = "#333333".zm.hex()
            cell.price.textColor = "#333333".zm.hex()
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        optionArr.forEach({$0.select = false})
        optionArr[indexPath.row].select = true
        collectionView.reloadData()
    }
}

extension PowerAddVC: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
            let imgSize = """
            var imgs = document.getElementsByTagName("img")
            for (var i = 0; i < imgs.length; i++) {
                imgs[i].setAttribute('width', '99%')
            }
            """
            webView.evaluateJavaScript(imgSize, completionHandler: nil)
            
            webView.evaluateJavaScript("""
                      var oMeta = document.createElement('meta');
                      oMeta.content = 'width=device-width, initial-scale=1.0, user-scalable=0';
                      oMeta.name = 'viewport';
                      document.getElementsByTagName('head')[0].appendChild(oMeta);
                      """) { flag, error in }
        }
        
    }
}

// MARK: - Request Action
extension PowerAddVC {
    func requestOption() {
        ZMToast.showActivity()
        PowerAPI.power_option.rxRequestNullAble(type: [PowerOptionModel].self).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            if let data = resp {
                self.optionArr = data
                self.optionCollection.reloadData()
                self.optionHeight.constant = self.optionCollection.collectionViewLayout.collectionViewContentSize.height
            } else {
                ZMToast.showToast(title: "获取充值面额失败")
            }
        }).disposed(by: disposeBag)
    }
    
    func requestCreate(_ info: PowerOptionModel, _ account: String) {
        ZMToast.showActivity()
        PowerAPI.power_order_create(["denominationId": info.id, "payType":"alipay", "account":account, "province": cityArr[0], "city": cityArr[1]]).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            self.showPay(money: info.sellPrice.zm.toString(keep: 2), orderNo: JSON(resp)["orderNo"].stringValue)
        }).disposed(by: disposeBag)
    }
    
    func requestWeb() {
        CommonAPI.getDetail(12).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
            let json = JSON(resp)
            self.wkWeb.loadHTMLString(json["content"].stringValue.zm.htmlBigSizeString(), baseURL: nil)
        }).disposed(by: disposeBag)
    }
}
